#!/bin/bash

#####
# Install z-hushitong startup script into /etc/init.d folder. z-hushitong will start processes automatically if machine reboots.
# Also install hst-app-monitor.sh script as a cron job, checking hushitong health care system processes every 5mins. If any process 
# is found dead this hst-app-monitor.sh will restart it.
#####

# Make sure root user to install
if [ "$(id -u)" != "0" ]; then
  echo "Not root user. Please change to root"
  exit 1
fi

# Setup auto start
if [ ! -f /opt/hushitong/z-hushitongapp ]; then
  echo "RC script /opt/hushitong/z-hushitongapp does not exist. Please check"
  exit 1
fi

cp -rf /opt/hushitong/z-hushitongapp /etc/init.d/.
chmod 755 /etc/init.d/z-hushitongapp
update-rc.d z-hushitongapp remove
update-rc.d z-hushitongapp defaults

# Setup cron job monitoring processes running every 5mins
if [ ! -x /opt/hushitong/hst-app-monitor.sh ]; then
  echo "cron script /opt/hushitong/hst-app-monitor.sh does not exist or has not execute permission. Please check"
  exit 1
fi
#echo "*/5 * * * * /opt/hushitong/hst-app-monitor.sh >> /var/log/hst-app-monitor.log 2>&1" > /var/spool/cron/crontabs/root
#echo "*/5 * * * * /opt/hushitong/hst-app-monitor.sh >/opt/hushitong/logs/hst-app-monitor.log 2>&1" > /var/spool/cron/crontabs/root
echo "*/5 * * * * /opt/hushitong/hst-app-monitor.sh" > /var/spool/cron/crontabs/root
chmod 0600 /var/spool/cron/crontabs/root
sed -i "s/^#cron/cron/g" /etc/rsyslog.d/50-default.conf
service rsyslog restart
service cron restart
